package club.banyuan.security;

import club.banyuan.bean.User;
import club.banyuan.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@Primary
public class MyUserDetailsService implements UserDetailsService {
    private UserDao userDao;
    private PasswordEncoder passwordEncoder;

    @Autowired
    public MyUserDetailsService(UserDao userDao, PasswordEncoder passwordEncoder) {
        this.userDao = userDao;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        System.out.println("XXXXXXXX load user by username XXXXXXXXXX");
        User dbUser = userDao.getUserByUserName(username);

        if (dbUser == null) {
            throw new UsernameNotFoundException(username + "Not Found");
        }
        return new MyUserDetails(dbUser);
    }
}
